/*
 * main.c
 *
 *  Created on: Feb 19, 2013
 *      Author: justin
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
unsigned short crc16_update(unsigned short crc, unsigned char a) {
	int i;
	/**This is the core CRC16 algorithm
	 * A01 OR's new value with the previous iteration
	 * A02 steps the function through the bits of the input byte
	 * A03 is used to determine if a remainder of zero exists
	 * A04 shifts the input from the previous call, and then
	 * OR's this with the Generator
	 * */
	crc ^= a;							//A01
	for (i = 0; i < 8; ++i) {			//A02
		if (crc & 1)					//A03
			crc = (crc >> 1) ^ 0xA001;    //A04
		else crc = (crc >> 1);			//A05
	}

	return crc;
}

int main(int argc, char *argv[]) {
	/*parse the input for input stream, then procede to */
	/**
	 * This is the adapted MCU code from the crc16 algorithm.
	 * The code within crc_16update remains unchanged,
	 * though the calling function has been modified such
	 * that it can accomodate either console
	 * input, or arguments referring to a file
	 * */
	if (argc > 1) {

		FILE *crcfile;
		crcfile = fopen(argv[2],"r");


		if (crcfile == NULL ) {
			printf("could not open file %s ",argv[1]);
			return EXIT_FAILURE;
		}
		else {
//			int filemode=1;
		}
	}

	printf("argcount=%d",argc);

	printf("display mode\nEnter a string on which to perform crc16.\n");
	unsigned char i, displayTemp[90];
	scanf("%s",displayTemp);
	printf("printing intermediate values");
	unsigned short crc = 0x0000;		//change to 0xffff for modbus initializer
//	int stringLlength=0;
	for (i = 0; i < (strlen(displayTemp)); ++i) {
		crc = crc16_update(crc,displayTemp[i]);
		printf("\n#%d current char='%.1s'\thex:0x%.2X\tdec:0d%d",i+1,&displayTemp[i],crc,crc);
	}

//	fclose(crcfile);
	return EXIT_SUCCESS;
}

